<?php

App::uses('AppModel', 'Model');

class ServiceCharge extends AppModel {

    public $name = 'ServiceCharge';
    
    public $belongsTo = array(
        'Transaction' => array(
            'className' => 'Transaction',
            'foreignKey' => 'transaction_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'AcademicSession' => array(
            'className' => 'AcademicSession',
            'foreignKey' => 'academic_session_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public function save($data = null,$validate = true, $fieldList = array()) {
        $s = $this->sanitize($data);
        return parent::save($s);
    }

    function getCisBills($start_dt,$end_dt,$type='details'){
        $service_data = $this->_getBills($start_dt,$end_dt);
        $arr = array();
        $arr_temp = array();
        foreach($service_data as $dt){
            $bill = doubleval($dt['ServiceCharge']['cis_amt']);
            if($type == 'consolidated'){
                $year_month = date("Y-m", strtotime($dt['ServiceCharge']['created']));
                $ob = isset($arr_temp[$year_month][0]['bill']) ? doubleval($arr_temp[$year_month][0]['bill']):0.00 ;
                $new_bill = $ob + $bill;
                $arr_temp[$year_month][0] =  array(
                    'date' => $year_month,
                    'bill' => $new_bill,
                );
            }
            else{
                $arr[] =  array(
                    'date' => $dt['ServiceCharge']['created'],
                    'bill' => $bill,
                );
            }
        }

        if($type == 'consolidated'){
            foreach($arr_temp as $k => $d1){
                foreach($d1 as $k1 => $d2){
                    $arr[] =  array(
                        'date' => $d2['date'],
                        'bill' => $d2['bill'],
                    );
                }
            }
        }

        return $arr;
    }

    function _getBills($start_dt,$end_dt){
        $conditions = array('ServiceCharge.payment_form' => 'invoice');
        $conditions['DATE(ServiceCharge.created) >='] = $start_dt;
        $conditions['DATE(ServiceCharge.created) <='] = $end_dt;
        $service_data = $this->find('all', array(
            'conditions' => $conditions,
            'recursive'=>-1
        ));

        return $service_data;
    }
}